<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 偏好设置控制器
 *
 * @desc    商户偏好设置控制器
 *
 * @desc    完善文档注释
 * @version 1.1.0
 * @date	2017年6月27日 下午5:35:08
 *
 * @title 商户偏好设置编辑
 * @entry http://discovery.segway.com
 */
class Setting extends MY_Business_Controller
{
	public function __construct()
	{
		parent::__construct();
		
		$this->member_id = @$this->get_logined_member()['id'];
		$this->merchant_id = @$this->get_logined_member()['MY_MERCHANT']['id'];
		
	}
	
	/**
	 * 首页 -> 设置语言货币时间 - 编辑前信息载入
	 *
	 * @return html
	 */
	public function index()
	{
		//$this->load->view('business/setting/index');
		$this->preferences();
	}
	
	/**
	 * 设置语言货币时间 - 编辑前信息载入
	 *
	 * @desc    编辑前信息载入
	 * @method  GET
	 * @author  Jason
	 * @date	2017年5月31日 下午1:59:41
	 * 
	 * @return  html
	 *
	 * @link /business/setting/preferences
	 */
	public function preferences()
	{
		$preferences = $this->get_logined_member()['MY_SETTINGS'];
		$data['preferences'] = $preferences;
		$data['mappings'] = [
				'language' => $this->config->item('supported_languages', 'multi_language'),
				'currency' => $this->config->item('supported_currencies', 'multi_currency'),
				'timezone' => $this->config->item('supported_timezones', 'multi_timezone'),
		];
		
		$this->load->view('business/setting/preferences', $data);
	}
	
	/**
	 * 设置语言货币时间 - 编辑完后的信息提交
	 *
	 * @desc    编辑完后的信息提交
	 * @method  POST
	 * @author  Jason
	 * @date	2017年5月31日 下午2:03:00
	 *
	 * @param   string $language 语言标识，选填项！
	 * @param   string $currency 币种标识, 选填项!
	 * @param   string $timezone 时区标识, 选填项!
	 *
	 * @return  JSON	标准JSON格式响应
	 * 					结构：无
	 *
	 * @link    /business/setting/ajax_set_preferences
	 * 
	 * @command noneurl
	 */
	public function ajax_set_preferences()
	{
		$preferences = $this->get_logined_member()['MY_SETTINGS'];
		foreach ($this->input->post() as $key => $value) {
			if (in_array($key, ['language', 'currency', 'timezone'])) {
				$preferences[$key] = $value;
			}
		}
		
		$this->load->library('business/lib_passport_merchant');
		$this->lib_passport_merchant->set_preferences($this->member_id, $preferences);
		$this->preferences_handler($preferences);
		
		// FIXME 语言的即时切换
		$_GET['lang'] = $preferences['language'];
		$this->language_handler();
		$this->view_handler();
		$data = [
				'refresh_url' => site_url('business/setting/preferences'),
		];
		Lib_json::renderSuccess($data);
	}
	
	private function preferences_handler($preferences)
	{
		// 刷新 SESSION
		# $this->CI->session->LOGINED_MEMBER['MY_SETTINGS'] = $preferences;
		$member = $this->get_logined_member();
		$member['MY_SETTINGS'] = $preferences;
		$this->session_construct_handler($member);
		// 设置 COOKIE
		$this->load->library('lib_cookie');
		$this->lib_cookie->set_language($preferences['language']);
		$this->lib_cookie->set_currency($preferences['currency']);
		$this->lib_cookie->set_timezone($preferences['timezone']);
	}
}
